import { Button, message, Tag, Popconfirm, Switch, Select } from 'antd';
import React, { useState, useRef } from 'react';
import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import DetailsForm from './components/DetailsForm';
import FilterSearch from './components/FilterSearch';

import {
  removeESIndex,
  backUpESIndex,
  queryESIndexDetail,
  queryESIndexList,
  sysnESIndex,
  operESStatus,
  delBatchES,
} from './service';
import './monitor.less';

// import {PlusOutlined} from "@ant-design/icons";

const TableList = () => {
  const actionRef = useRef();
  const [detailModalVisible, handleDetailModalVisible] = useState(false);
  const [filterModalVisible, handleFilterModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [removing, setRemoving] = useState(false);
  const [status, setStatus] = useState([]);
  const { Option } = Select;
  const [selectedRowsState, setSelectedRows] = useState([]);
  /**
   * 索引同步
   * @returns {Promise<boolean>}
   */
  const handleESIndexSysnc = async () => {
    const hide = message.loading('正在同步', 0);
    try {
      await sysnESIndex({
        type: 'hive',
      });
      hide();
      message.destroy();
      message.success('同步索引成功');
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (e) {
      hide();
      message.error('同步索引失败请重试！');
    }
  };

  /**
   *  删除esIndex
   * @param selectedRows
   */

  const handleRemove = async (params) => {
    if (removing) {
      message.warning({ content: '其他索引在删除中，请稍后重试' });
      return;
    }
    if (params.backup !== '0') {
      message.error('该索引未备份，请先备份再删除');
      return;
    }
    message.loading('正在删除', 0);
    setRemoving(true);
    await removeESIndex({
      index: params.index,
      type: 'hive',
    })
      .then((res) => {
        if (res.status === 200) {
          setRemoving(false);
          message.destroy();
          message.success('删除成功');
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          setRemoving(false);
          message.destroy();
          message.error(res.message);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      })
      .catch(() => {
        setRemoving(false);
        message.destroy();
        message.error('删除失败');
        if (actionRef.current) {
          actionRef.current.reload();
        }
      });
  };
  /**
   * 备份esIndex
   * @param fields
   */

  const handleBackUp = async (param) => {
    /*    if (backUpLoading) {
          message.warning({ content: '其他索引在备份中，请稍后重试' });
          return false;
        } */
    await backUpESIndex({
      index: param.index,
      type: 'hive',
    })
      .then((res) => {
        if (res.status === 200) {
          message.loading(res.message);
        } else {
          message.warn(res.message);
        }
        return true;
      })
      .catch(() => {
        message.error('备份失败');
        return true;
      });
    return true;
  };

  const handleStatusChange = (record, index, checked) => {
    const statusCopy = [...status];
    statusCopy[index] = checked;
    setStatus(statusCopy);
    operESStatus({
      id: record.id,
      checked,
      index: record.index,
      type: 'hive',
    }).then((res) => {
      if (res.status === 200) {
        message.info(res.message);
      } else {
        message.error(res.message);
      }
      if (actionRef.current) {
        actionRef.current.reload();
      }
    });
  };
  /**
   * 处理列表查询的返回值
   * @param datas
   * @returns {*}
   */
  const handleDatas = (datas) => {
    const statusCopy = datas.map((item) => item.status);
    setStatus(statusCopy);
    return datas;
  };
  /**
   *  查看esIndex
   * @param selectedRows
   */

  const handleDetail = async (row) => {
    const hide = message.loading('正在查找');
    try {
      await queryESIndexDetail({
        index: row.index,
        type: 'hive',
      });
      hide();
      message.success('查找成功，即将刷新');
      return true;
    } catch (error) {
      hide();
      message.error('查找失败，请重试');
      return false;
    }
  };

  /**
   *  批量删除
   * @param selectedRows
   */

  const handleDelBatch = async (selectedRows, delType) => {
    message.loading({ content: '正在批量删除', duration: 0 });
    if (!selectedRows) return true;
    await delBatchES({
      logIdList: selectedRows.map((row) => row.id),
      delType,
      type: 'hive',
    })
      .then((res) => {
        if (res.code === 200) {
          message.destroy();
          message.success('批量删除成功');
          return true;
        }
        message.destroy();
        message.error('批量删除失败请重试');
        return false;
      })
      .catch(() => {
        message.destroy();
        message.error('批量删除失败请重试');
        return false;
      });
    return true;
  };

  const columns = [
    {
      title: 'UUID',
      dataIndex: 'uuid',
      key: 'uuid',
      sorter: false,
    },
    {
      title: '索引名称',
      key: 'index',
      dataIndex: 'index',
    },
    {
      title: '索引大小',
      key: 'store.size',
      dataIndex: 'store.size',
      sorter: false,
      search: false,
    },
    {
      title: '文档数量',
      key: 'docs.count',
      dataIndex: 'docs.count',
      sorter: false,
      search: false,
    },
    {
      title: '监控状态',
      key: 'health',
      dataIndex: 'health',
      sorter: true,
      search: false,
      render: (text, record) => {
        const color = text === 'green' ? '#009688' : '#ff4d4f';
        const colorVal = text === 'green' ? 'green' : 'red';
        return (
          <Tag color={color} key={record.id}>
            {colorVal}
          </Tag>
        );
      },
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      sorter: true,
      renderFormItem: () => {
        return (
          <Select
            key="deleteSelect"
            showSearch
            placeholder="请选择状态"
            filterOption={false}
            defaultValue=""
          >
            <>
              <Option key="all" value="">
                全部
              </Option>
              <Option key="open" value="open">
                开启
              </Option>
              <Option key="close" value="close">
                关闭
              </Option>
            </>
          </Select>
        );
      },
      render: (text, record, index) => {
        const disabledVal = record.delete === '1';
        return (
          <Switch
            checkedChildren="开启"
            unCheckedChildren="关闭"
            checked={status[index] === 'open'}
            onChange={(checked) => handleStatusChange(record, index, checked)}
            disabled={disabledVal}
          />
        );
      },
    },
    {
      title: '是否删除',
      key: 'delete',
      dataIndex: 'delete',
      sorter: true,
      renderFormItem: () => {
        return (
          <Select
            key="deleteSelect"
            showSearch
            placeholder="请选择删除状态"
            filterOption={false}
            defaultValue=""
          >
            <>
              <Option key="2" value="">
                全部
              </Option>
              <Option key="0" value="0">
                未删除
              </Option>
              <Option key="1" value="1">
                已删除
              </Option>
            </>
          </Select>
        );
      },
      render: (text, record) => {
        const color = record.delete === '0' ? '#009688' : '#ff4d4f';
        return (
          <Tag color={color} key={record.status}>
            {record.delete === '0' ? '未删除' : '已删除'}
          </Tag>
        );
      },
    },
    {
      title: '备份状态',
      key: 'backup',
      dataIndex: 'backup',
      sorter: true,
      hideInTable: true,
      renderFormItem: () => {
        return (
          <Select
            key="backupSelect"
            showSearch
            placeholder="请选择备份状态"
            filterOption={false}
            defaultValue=""
          >
            <>
              <Option key="3" value="">
                全部
              </Option>
              <Option key="1" value="1">
                未备份
              </Option>
              <Option key="2" value="2">
                备份中
              </Option>
              <Option key="0" value="0">
                已备份
              </Option>
            </>
          </Select>
        );
      },
    },
    {
      title: '备份时间',
      key: 'backUpTime',
      dataIndex: 'backUpTime',
      sorter: false,
      search: false,
    },
    {
      title: '操作',
      key: 'option',
      dataIndex: 'option',
      valueType: 'option',
      render: (text, record) => {
        let backUpColorVal = record.backup === '1' ? '#FFB800' : '#808A87';
        let filterColorVal = record.backup === '0' ? '#009688' : '#808A87';
        let backUpDisabledVal = record.backup !== '1';
        let filterDisabledVal = !backUpDisabledVal;
        const backUpVal = record.backup === '2' ? '备份中' : '备份';
        let deleteColorVal = record.delete === '1' ? '#808A87' : '';
        let deleteDisabledVal = record.delete === '1';
        if (record.backup === '3' || record.status === 'close') {
          backUpColorVal = '#808A87';
          backUpDisabledVal = true;
          deleteColorVal = '#808A87';
          deleteDisabledVal = true;
          filterColorVal = '#808A87';
          filterDisabledVal = true;
        }
        return (
          <>
            <Button
              type="primary"
              size="small"
              onClick={() => {
                handleDetailModalVisible(true);
                setStepFormValues(record);
              }}
            >
              查看
            </Button>
            &nbsp;
            <Button
              type="primary"
              size="small"
              style={{ background: backUpColorVal, borderColor: backUpColorVal }}
              disabled={backUpDisabledVal}
              onClick={async () => {
                const success = await handleBackUp(record);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              }}
            >
              {backUpVal}
            </Button>
            &nbsp;
            <Popconfirm title="确认删除吗?" onConfirm={() => handleRemove(record)}>
              <Button
                type="primary"
                size="small"
                danger
                style={{ background: deleteColorVal, borderColor: deleteColorVal }}
                disabled={deleteDisabledVal}
              >
                删除
              </Button>
              &nbsp;
            </Popconfirm>
            <Button
              type="primary"
              size="small"
              style={{ background: filterColorVal, borderColor: filterColorVal }}
              disabled={filterDisabledVal}
              onClick={() => {
                handleFilterModalVisible(true);
                setStepFormValues(record);
              }}
            >
              过滤
            </Button>
          </>
        );
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey={(record) => record.id}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleESIndexSysnc()} key={'esBtn'}>
            ES同步
          </Button>,
        ]}
        request={(params, sorter, filter, type = 'hive') =>
          queryESIndexList({ ...params, sorter, filter, type })
        }
        postData={handleDatas}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />

      {stepFormValues && Object.keys(stepFormValues).length && detailModalVisible ? (
        <DetailsForm
          key="esIndexModal"
          onSubmit={async (value) => {
            const success = await handleDetail(value);
            if (success) {
              handleDetailModalVisible(false);
              setStepFormValues({});
            }
          }}
          onCancel={() => {
            handleDetailModalVisible(false);
            setStepFormValues({});
          }}
          detailModalVisible={detailModalVisible}
          values={stepFormValues}
        />
      ) : null}

      {stepFormValues && Object.keys(stepFormValues).length && filterModalVisible ? (
        <FilterSearch
          key="esIndexFilterModal"
          onSubmit={async (value) => {
            const success = await handleDetail(value);
            if (success) {
              handleFilterModalVisible(false);
              setStepFormValues({});
            }
          }}
          onCancel={() => {
            handleFilterModalVisible(false);
            setStepFormValues({});
          }}
          filterModalVisible={filterModalVisible}
          values={stepFormValues}
        />
      ) : null}

      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项
            </div>
          }
        >
          <Popconfirm
            title="确认删除吗?"
            onConfirm={async () => {
              await handleDelBatch(selectedRowsState, 'delIndex');
              setSelectedRows([]);
              actionRef.current?.reloadAndRest();
            }}
          >
            <Button
              title={'该操作将从elk中删除该索引，且删除该索引的hadoop备份'}
              type="primary"
              danger
            >
              批量删除索引
            </Button>
          </Popconfirm>
          <Popconfirm
            title="确认删除吗?"
            onConfirm={async () => {
              await handleDelBatch(selectedRowsState, 'delES');
              setSelectedRows([]);
              actionRef.current?.reloadAndRest();
            }}
          >
            <Button title={'该操作仅从elk中删除该索引'} type="primary" danger>
              批量清空ES
            </Button>
          </Popconfirm>
          <Popconfirm
            title="确认删除吗?"
            onConfirm={async () => {
              await handleDelBatch(selectedRowsState, 'delInnerDB');
              setSelectedRows([]);
              actionRef.current?.reloadAndRest();
            }}
          >
            <Button title={'该操作仅删除该索引的hadoop备份'} type="primary" danger>
              批量清空内部表
            </Button>
          </Popconfirm>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
